/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.ages.test.swat

import com.ages.entity.Actor
import com.ages.env.AbstractWorld
import com.ages.env.Options
import com.ages.graphics.SpriteBufferManager
import com.ages.graphics.HudText
import com.ages.graphics.Sprite
import com.ages.graphics.ViewportSwitcher
import java.util.Collections
import javax.media.opengl.GL
import javax.media.opengl.glu.GLU
import scala.collection.mutable.ArrayBuffer
import scala.collection.mutable.Queue

object SwatWorld{
    val spr:Sprite = new Sprite("/com/ages/test/res/picnicjello.png",1,1,1)
}

class SwatWorld(player:Swatter) extends AbstractWorld with SpawnListener{

  var score = 0.0
  var swatsPerMinute = 0.0
  var timePassed = 0.0
  val startTime = System.currentTimeMillis
  val MINUTE = 60000
  val addQueue = new Queue[Actor]()
  newWorldObject(new BlackFade)//fade in this world

  def newWorldObject(a:Actor){
    addQueue+=a
  }

  def increaseScore { score+=1 }

  override def addEntity(a:Actor)
  {
    super.addEntity(a)
    if(a.isInstanceOf[Fly])
    {
      a.asInstanceOf[Fly].addSpawnListener(this)
    }
    if(a.isInstanceOf[Swatter])
    {
      a.asInstanceOf[Swatter].addSpawnListener(this)
    }
        if(a.isInstanceOf[Wasp])
    {
      a.asInstanceOf[Wasp].addSpawnListener(this)
    }

  }

  override def think() {
//  println("swatworld thinking")
    timePassed = System.currentTimeMillis-startTime

    swatsPerMinute = score/(timePassed/MINUTE)

    actors = actors.sortWith(_>_)

    for(a<-actors)
    {
      a.think
    }

    for(i<-0 until actors.length)
    {
      for(j<-i+1 until actors.length)
      {
        val a = actors(i)
        val b = actors(j)
        if(a.collidesWith(b)||b.collidesWith(a))
        {
          a.handleCollision(b)
          b.handleCollision(a)
        }
      }
    }

    var i = 0
    while(i<actors.size)
    {
      val a = actors(i)
      if(a.markedForDeletion)
      {
        actors.remove(i)
      }
      i+=1
    }
    while(!addQueue.isEmpty)
    {
      addEntity(addQueue.dequeue)
    }
  }
  override def draw(gl:GL){
//  println("swatworld drawing")
    gl.glPushMatrix
    gl.glTranslated(0,-424,0)
    gl.glColor4d(1,1,1,1)
    SwatWorld.spr.drawWithoutDisplaylist(gl,0,0)
    gl.glPopMatrix

    val glu = new GLU()
    for(a<-actors)
    {
      a.draw(gl)
    }
//    player.draw(gl)

    val time = 60-(Math.abs(startTime - System.currentTimeMillis)/1000)
    HudText.draw(gl,"S.W.A.T.'s: "+score+", FPM: "+swatsPerMinute.floor,10,30)
    HudText.draw(gl,"Number of actors: "+actors.size,10,50)
    HudText.draw(gl,"Time Left:"+ time,10,80)

    SpriteBufferManager.bufferQueue(gl)

    if(time<0)
      {
        for(wl<- worldListeners)
          {
            wl.worldFinished(new GameOverWorld())
          }
      }
  }
  def worldDone = true
}


